﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DLM.Web.MVC.Models;
using DLM.Domain.Model;
using DLM.Services.Interfaces;
using DLM.Web.ViewModel;
using Webdiyer.WebControls.Mvc;

namespace DLM.Web.MVC.Areas.Management.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Management/Account/

        private IAdminService adminService;

        public AccountController(IAdminService adminService)
        {
            this.adminService = adminService;
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateMvcCaptcha]
        public ActionResult Login(AdminUser admin)
        {
            if (ModelState["_mvcCaptchaText"] != null && ModelState["_mvcCaptchaText"].Errors.Count > 0)
            {
                ModelState.AddModelError("", "验证码不匹配，请重新输入！");
                return View();
            }
            if (string.IsNullOrEmpty(admin.Administrator))
            {
                ModelState.AddModelError("Administrator", "账号不允许为空！!");
                return View();
            }
            try
            {
                this.adminService.Login(admin);
                return RedirectToAction("Index", "Main");
            }
            catch (System.Security.Authentication.InvalidCredentialException)
            {
                ModelState.AddModelError("Administrator", "账户不存在或者密码错误!");
                return View();

            }

            return View();
        }

        [HttpPost]
        public ActionResult LogOut()
        {
            this.adminService.LogOut();
            return Content("");
        }

        [HttpGet]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(AdminUser admin, FormCollection collection)
        {

            {
                var confirmedPass = collection["txtConfirmedPass"].ToString();
                if (admin.Password == confirmedPass)
                {
                    try
                    {
                        this.adminService.ChangePassword(User.Identity.Name, admin.Password, confirmedPass);
                    }
                    catch (Exception ex)
                    {

                        ModelState.AddModelError("", ex.Message);
                        return View();
                    }

                }
                else
                {
                    ModelState.AddModelError("Password", "两次输入的密码不一致，请检查！");
                    return View();
                }
                return View();
            }



        }
    }
}
